import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/core/models/store_categories.dart';
import 'package:mall/screens/product/product_category_screen.dart';
import 'package:mall/screens/store/store_category_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../theme.dart';
import 'home_category_screen.dart';

class HomeSearchScreenArgs {
  final int storeId;
  final int categoryId;
  final int areaId;

  HomeSearchScreenArgs({
    this.storeId,
    this.categoryId,
    this.areaId,
  });
}

/// 商品搜索页面
class HomeSearchScreen extends StatefulWidget {
  static const routeName = "/HomeSearchScreen";
  final HomeSearchScreenArgs args;

  const HomeSearchScreen({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  _HomeSearchScreenState createState() => _HomeSearchScreenState();
}

class _HomeSearchScreenState extends State<HomeSearchScreen> {
  static const _SEARCH_HISTORY = "search_history";
  List<String> _list = [];
  Category _category;

  @override
  void initState() {
    super.initState();
    _loadSearchHistory();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _buildSearchField(),
        titleSpacing: 0,
        actions: [
          if (widget.args.storeId != null)
            FlatButton(
              minWidth: 0,
              onPressed: _onTapCategory,
              child: Text("${_category?.name ?? "分类"}"),
            ),
        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.all(14.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(4.w),
          ),
          margin: EdgeInsets.all(8.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("历史搜索"),
                  GestureDetector(
                    onTap: _clearSearchHistory,
                    child: Text("清除"),
                  ),
                ],
              ),
              SizedBox(height: 16.w),
              Wrap(
                spacing: 6.w,
                runSpacing: 10.w,
                children: List.generate(_list.length, (index) => _buildItem(_list[index])),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildItem(String text) {
    return GestureDetector(
      onTap: () => _onTapItem(text),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 6.w, horizontal: 10.w),
        decoration: BoxDecoration(
          color: Theme.of(context).scaffoldBackgroundColor,
          borderRadius: BorderRadius.circular(15.w),
        ),
        child: Text("$text"),
      ),
    );
  }

  Container _buildSearchField() {
    final outlineInputBorder = OutlineInputBorder(
      borderSide: BorderSide(color: kLineColor),
      borderRadius: BorderRadius.circular(15.w),
    );
    return Container(
      margin: EdgeInsets.all(8.w),
      height: 25.w,
      child: TextField(
        decoration: InputDecoration(
          prefixIcon: Icon(Icons.search, color: Colors.black),
          hintText: widget.args.storeId == null ? "搜索" : "店铺搜索",
          contentPadding: EdgeInsets.zero,
          focusedBorder: outlineInputBorder,
          enabledBorder: outlineInputBorder,
          border: outlineInputBorder,
          isDense: true,
        ),
        textInputAction: TextInputAction.search,
        onSubmitted: _search,
      ),
    );
  }

  /// 搜索
  void _search(String text) async {
    if (text == null || text.isEmpty) {
      return;
    }
    await _saveSearchHistory(text);
    // 复用
    _onTapItem(text);
  }

  /// 获取搜索历史
  void _loadSearchHistory() async {
    final pref = await SharedPreferences.getInstance();
    final list = pref.getStringList(_SEARCH_HISTORY);
    setState(() {
      _list.addAll(list ?? []);
    });
  }

  /// 保存搜索历史
  Future _saveSearchHistory(String text) async {
    setState(() {
      _list.remove(text);
      _list.insert(0, text);
    });
    final pref = await SharedPreferences.getInstance();
    await pref.setStringList(_SEARCH_HISTORY, _list);
  }

  /// 清除搜索历史
  void _clearSearchHistory() async {
    setState(() {
      _list.clear();
    });
    final pref = await SharedPreferences.getInstance();
    pref.remove(_SEARCH_HISTORY);
  }

  /// 点击历史
  void _onTapItem(String text) {
    // 转到搜索结果页面
    Navigator.of(context).pushNamed(
      ProductCategoryScreen.routeName,
      arguments: ProductCategoryScreenArgs(
        text,
        storeId: widget.args.storeId,
        categoryId: _category?.id ?? widget.args.categoryId,
        areaId: widget.args.areaId,
        queryKey: text,
      ),
    );
  }

  /// 点击分类
  void _onTapCategory() async {
    // 这里需要区分首页还是店铺，根据有没有storeId
    Category category;
    if (widget.args.storeId == null) {
      // 首页
      category = await Navigator.of(context).pushNamed(
        HomeCategoryScreen.routeName,
        arguments: HomeCategoryScreenArgs(true),
      );
    } else {
      // 店铺
      category = await Navigator.of(context).pushNamed(
        StoreCategoryScreen.routeName,
        arguments: StoreCategoryScreenArgs(widget.args.storeId, true),
      );
    }
    // 判断返回值并刷新显示
    if (category == null) {
      return;
    }
    setState(() {
      _category = category;
    });
  }
}
